﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using blackhouse.Data;
using blackhouse;

namespace blackhouse.BlackApart.Data.Sql {
    public class LineReservationServiceSaveTransaction : ReservationServiceSaveTransaction {

        #region Fields

        private MsSqlAdoDataHelper dataHelper;

        #endregion

        #region Constructors

        public LineReservationServiceSaveTransaction(string connSql) {
            this.dataHelper = new MsSqlAdoDataHelper(connSql);
        }

        #endregion

        #region Methods

        public override int Save() {

            bool trybD = (this.saveVariant & 0x1) == 0x1;
            bool trybP = (this.saveVariant & 0x2) == 0x2;
            bool trybI = (this.saveVariant & 0x4) == 0x4;

            List<string> sbLines = new List<string>();

            if (this.lines.Count == 0 && this.saveVariant == 0)
                this.lines.Add(new TransactionLine());

            foreach (TransactionLine line in this.lines) {
                sbLines.Add(this.ConstructLine(line.ForDate, line.ApartmentId, line.Quantity, trybD, trybP, trybI, "null"));
            }

            this.dataHelper.Reset();
            this.dataHelper.ProcedureName = "DST_USLUGA_ADD";
            this.dataHelper.AddParameter("id_uzytkownika", 9000009, DbType.Int32);
            this.dataHelper.AddParameter("idx_usluga_pozycja", 0, DbType.Int32);
            this.dataHelper.AddParameter("idx_rezerwacja", this.reservationId, DbType.Int32);
            this.dataHelper.AddParameter("idx_usluga", this.serviceId, DbType.Int32);
            this.dataHelper.AddParameter("cena", this.unitPrice, DbType.Double);
            this.dataHelper.AddParameter("uwagi", this.clientReview, DbType.String);
            this.dataHelper.AddParameter("tryb", this.saveVariant, DbType.Int32);
            this.dataHelper.AddParameter("line", string.Join(",", sbLines.ToArray()), DbType.String);
            object orderId = this.dataHelper.ExecuteProcedureResult();
            if (orderId != null)
                return Convert.ToInt32(orderId);
            else
                return 0;
        }

        private string ConstructLine(DateTime date, int apartmentId, int quantity, bool d, bool p, bool i, string notAllowedValue) {
            string[] lineParts = new string[3];
            lineParts[0] = (d) ? date.GetSqlNumDate().ToString() : notAllowedValue;
            lineParts[1] = (p) ? apartmentId.ToString() : notAllowedValue;
            lineParts[2] = (i) ? quantity.ToString() : notAllowedValue;
            return string.Join(",", lineParts);
        }

        #endregion

    }
}
